import * as ActionTypes from '../constants/ActionTypes';
const $ = require('jquery');
const fs = require('fs');
let payloadData;
let childTree;
let jsonTree;

function addFileTree(data) {
  return {
    'type': ActionTypes.ADD_FILE_TREE,
    'payload': data,
  };
}

function addChildrenTree(data) {
  return {
    'type': ActionTypes.ADD_CHILDREN_TREE,
    'payload': data,
  };
}

function addJsonTree(data) {
  return {
    'type': ActionTypes.ADD_JSON_FILE,
    'payload': data,
  };
}

async function testDir(f, dispatch) {
  return new Promise((resolve, reject) => {
    fs.stat(f.path, async function (err, stat) {
      if (err) {
        console.error(err);
        reject(err);
        throw err;
      }
      let splitArr;
      let dirname;
      if (f.path.indexOf('\\') > -1) {
        splitArr = f.path.split('\\');
        dirname = splitArr[splitArr.length - 1];
      } else if(f.path.indexOf('/') > -1) {
        splitArr = f.path.split('/');
        dirname = splitArr[splitArr.length - 1];
      }
      stat.isFile() && payloadData.push({ 'key': payloadData.length, 'path': f.path, 'isLeaf': true, 'title': dirname });
      stat.isDirectory() && payloadData.push({ 'key': payloadData.length, 'path': f.path, 'isLeaf': false, 'title': dirname });
      resolve('success');
    });
  });
}

async function readJsonFile(path) {
  return new Promise((resolve, reject) => {
    fs.readFile(path, 'utf8', function (errors, data) {
      if (errors || !data) {
        reject(errors);
      } else {
        resolve(JSON.parse(data));
      }
    });
  });
}


async function addChildTree(path, dispatch, key) {
  return new Promise((resolve, reject) => {
    fs.stat(path, async function (err, stat) {
      if (err) {
        console.error(err);
        reject(err);
        throw err;
      }
      let splitArr;
      let dirname;
      if (path.indexOf('\\') > -1) {
        splitArr = path.split('\\');
        dirname = splitArr[splitArr.length - 1];
      } else if(path.indexOf('/') > -1) {
        splitArr = path.split('/');
        dirname = splitArr[splitArr.length - 1];
      }
      stat.isFile() && (/\.dat$/.test(path)) && childTree.push({ 'key': key + '-' + childTree.length, 'path': path, 'isLeaf': true, 'title': dirname });
      stat.isDirectory() && childTree.push({ 'key': key + '-' + childTree.length, 'path': path, 'isLeaf': false, 'title': dirname });
      if (stat.isFile() && (/\.json$/.test(path))) {
        readJsonFile(path).then((data) => {
          const delEvent = [];
          const eventKeysArr = Object.keys(data.event);
          const eventValuesArr = Object.values(data.event);
          const newEventValue = eventValuesArr.map((item, index) => {
            const newItem = item.map((ele, index2) => {
              let eventName;
              let obj = {};
              switch (eventKeysArr[index]) {
                case "offbed":
                  eventName = '离床';
                  break;
                case "apnea":
                  eventName = '呼吸暂停';
                  break;
                default:
                  eventName = '';
                  break;
              }
              obj.eventName = eventName;
              return Object.assign({}, ele, obj);
            });
            return newItem;
          });
          let dealedArr = [];
          for (let i = 0, len = eventKeysArr.length; i < len; i++) {
            dealedArr = [...dealedArr, ...newEventValue[i]];
          }
          dealedArr.forEach((item, index) => {
            const delObj = {};
            delObj.key = index;
            delObj.eventName = item.eventName;
            delObj.timeStart = item.timeStart;
            delObj.timeEnd = item.timeEnd;
            delEvent.push(delObj);
          });
          jsonTree[path] = ({ 'path': path, tags: data.tags, event: delEvent });
          resolve('success');
        })
      } else {
        resolve('success');
      }
    });
  });
}

export function listenDrag() {
  return function (dispatch) {
    $(document).off('drop').on('drop', async function (e) {
      e.dataTransfer = e.originalEvent.dataTransfer;
      e.preventDefault();
      e.stopPropagation();
      payloadData = [];
      $('body').css('opacity', 1);
      for (let f of e.dataTransfer.files) {
        await testDir(f, dispatch);
      }
      dispatch(addFileTree(payloadData));
    });
    $(document).off('dragover').on('dragover', function (e) {
      $('body').css('opacity', 0.5);
      e.preventDefault();
      e.stopPropagation();
    });

    $(document).off('dragleave').on('dragleave', function (e) {
      $('body').css('opacity', 1);
      e.preventDefault();
      e.stopPropagation();
    });
  };
}

function readFileName(path) {
  return new Promise((resolve, reject) => {
    fs.readdir(path, function (err, files) {
      if (err) {
        reject(err);
      } else {
        resolve(files);
      }
    });
  });
}

export function loadChildTree(pathName, key) {
  childTree = [];
  jsonTree = {};
  return async function (dispatch) {
    let promiseArr = [];
    const listItemsArr = await readFileName(pathName);
    let newPath;
    for (let i = 0, len = listItemsArr.length; i < len; i++) {
      if (pathName.indexOf('\\') > -1) {
        newPath = pathName + '\\' + listItemsArr[i];
      } else if(pathName.indexOf('/') > -1) {
        newPath = pathName + '/' + listItemsArr[i];
      }
      promiseArr.push(addChildTree(newPath, dispatch, key)); 
    }
    Promise.all(promiseArr).then(async function () {
      await dispatch(addChildrenTree({'data': childTree, 'path': pathName, key}));
      await dispatch(addJsonTree(jsonTree));          
    })
  }
}
